import { _decorator, Component, EditBox, Node, input, Input, EventMouse } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('SerialWebSocketData')
export class SerialWebSocketData extends Component {


    @property(EditBox)
    editbox: EditBox | null = null;
    private ws: WebSocket | null = null;




    onLoad() {


        // 创建 WebSocket 连接  
        this.ws = new WebSocket('ws://localhost:8080');

        // 监听 WebSocket 连接打开事件  
        this.ws.onopen = (event) => {
            console.log('WebSocket connection opened');
            // 这里可以发送初始消息给服务器，如果需要的话  
            // this.ws.send('Hello Server!');  
        };

        // 监听 WebSocket 消息接收事件  
        this.ws.onmessage = (event) => {
            console.log('Received message from server:', event.data);
            // 处理接收到的数据，例如更新游戏状态  
            this.editbox.string = event.data;

        };

        // 监听 WebSocket 连接关闭事件  
        this.ws.onclose = (event) => {
            console.log('WebSocket connection closed:', event);
        };
        // 监听 WebSocket 错误事件  
        this.ws.onerror = (error) => {
            console.error('WebSocket error:', error);
        };
    }

    start() {
        input.on(Input.EventType.MOUSE_UP, this.onMouseUp, this);
    }
    onMouseUp(event: EventMouse) {

        this.ws.send("你好, I am from web");
    }


    update(deltaTime: number) {

    }


    onDestroy() {
        // 在组件销毁时关闭 WebSocket 连接  
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.close();
        }
    }


    // 你可以在这里添加其他方法，例如发送消息给服务器  
    sendMessageToServer(message) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(message);
        } else {
            console.warn('WebSocket connection is not open');
        }
    }


}


